/* global wp_map_maker_plugin_options, L */

var MapMaker = {
  map: null,
  geocoder: null,
  getSelectionHtml: function() {
    var html = "";
    if (typeof window.getSelection !== "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection !== "undefined") {
        if (document.selection.type === "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
  },
  placeMapButton: function () {
    var selection = window.getSelection(),
    range = selection.getRangeAt(0),
    boundary = range.getBoundingClientRect();
    var left = (boundary.left + boundary.right) / 2 - 30;
    var top = window.pageYOffset + boundary.top - 50;
    var template =
      '  <a href="#"><img src="'+wp_map_maker_plugin_options.img_url+'/map.png" alt="map button"/></a>' +
      '  <div class="map-maker-button-clip"><span class="map-maker-button-arrow"></span></div>';
    var button = jQuery('<div>').attr('class', 'map-maker-button').css({
      top: top,
      left: left
    }).html(template);
    jQuery(document.body).append(button);
  },
  placeMap: function () {
    // add map containter
    var mapContainer = jQuery('<div>').attr('id', 'map-maker');
    var template = '' +
    '<div id="map-maker-title">' +
          '<button type="button" class="map-maker-close close">×</button>' +
    '</div>' +
    '<div id="map-maker-map"></div>';
    mapContainer.html(template);
    jQuery('body').append(mapContainer);
    // map-maker-close button
    jQuery('.map-maker-close').on('click', function(e){
      e.preventDefault();
      jQuery('#map-maker').hide();
    });
  },
  showMap: function(err, data) {
    if (data.lbounds) {
        MapMaker.map.fitBounds(data.lbounds);
    } else if (data.latlng) {
        MapMaker.map.setView([data.latlng[0], data.latlng[1]], 13);
        L.marker(data.latlng).addTo(MapMaker.map);
    }
  },
};

jQuery(document).ready(function(){
  'use strict';
  MapMaker.placeMap();
  // bind mouseup event to detect address has been selected
  jQuery(document.body).on('mouseup', function () {
    // add map button when some text has been selected.
    if (window.getSelection()) {
      var text = MapMaker.getSelectionHtml();
      // check text content, don't use HTML content
      if (!text.match(/<.+>.*<\/.+>/) && text !== '' && !jQuery('.map-maker-button').length) {
        MapMaker.placeMapButton();
        // show the map and put the selected address marker
        jQuery('.map-maker-button').on('click', function (e) {
          e.preventDefault();
          if (! MapMaker.map) {
            MapMaker.map = L.mapbox.map('map-maker-map', wp_map_maker_plugin_options.mapID);
            MapMaker.geocoder = L.mapbox.geocoder(wp_map_maker_plugin_options.mapID);
          }
          jQuery('#map-maker').show();
          // if map and geocoder doesn't exist, we go to initialize. Otherwise, we show the map directly
          MapMaker.geocoder.query(text, MapMaker.showMap);
          jQuery(this).remove();
          window.getSelection().removeAllRanges();
        });
      }
    }
  });
});
